import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../../entity/user.entity'
import { JwtService } from '@nestjs/jwt'
// import { UserEntity } from './user.entity'
import {AuthService} from "../auth/auth.service";

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User)
        private readonly adminRepository: Repository<User>,
        private readonly jwtService: JwtService,
        // private readonly AuthService: AuthService,

        // @InjectRepository(UserEntity)
        // private readonly userRepository: Repository<UserEntity>,
        // @InjectRepository(UserRoleEntity)
    ) {}
    //序列化树路由
    treeData(source, id, parentId, children){
        let cloneData = JSON.parse(JSON.stringify(source))
        return cloneData.filter(father=>{
            let branchArr = cloneData.filter(child => father[id] == child[parentId]);
            branchArr.length>0 ? father[children] = branchArr : ''
            return father[parentId] == 0
        })
    }
    async login(email,password){
        // console.log(email)
        // console.log(password)
        const token = await this.createToken()
        return { statusCode: 200, message: '登录成功', data: token }
        // return await this.adminRepository.query(`SELECT * FROM user WHERE email = '${email}' AND password = '${password}'`)
    }
    // 根据用户id查询用户信息, 只查用户表，
    // async findOneById(id: number): Promise<UserEntity> {
    //     return await this.userRepository.findOne(id)
    // }
    async list(){
        return await this.adminRepository.find() //id与context存在一个即可查出数据 sql表中添加一个值
    }

    async path(name:string){
        return await this.adminRepository.query(`
        SELECT * FROM auth WHERE authid in (SELECT authid FROM role_auth WHERE roleid = (SELECT roleid FROM user where name = '${name}'))
        `);
    }
    private async createToken(): Promise<string> {
        const payload = {
            id: 4
        };
        return this.jwtService.sign(payload)
        // return this.AuthService.createToken(payload)
    }

}
